package leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class sanshuzhihe2 {
    public static List<List<Integer>> threeSum(int[] nums) {
        if(nums==null||nums.length<3){
            return null;
        }
        List<List<Integer>> list=new ArrayList<>();
        Arrays.sort(nums);
        for(int i=0;i<nums.length-2;){
            int a=nums[i];
            if(a>0){
                break;
            }
            int left=i+1;
            int right=nums.length-1;
            while(left<right){
                if(nums[left]+nums[right]>-a){
                    right--;
                }else if(nums[left]+nums[right]<-a){
                    left++;
                }else{
                    list.add(Arrays.asList(a,nums[left],nums[right]));
                    left++;
                    right--;
                    //对left与right进行去重,注意防止越界
                    while(left<right&&nums[left]==nums[left-1]){
                        left++;
                    }
                    while(left<right&&nums[right]==nums[right+1]){
                        right--;
                    }
                }

            }
            // 对a进行去重
            i++;
            while(nums[i]==nums[i-1]){
                i++;
            }
        }
        return list;

    }

    public static void main(String[] args) {
        int[] arrays={-2,0,1,1,2};
        List<List<Integer>> list = threeSum(arrays);
        System.out.println(list);
    }
}
